/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */   
    
package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.mysql.jdbc.Statement;
import com.ndp.fb.rdb.api.PageRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.Page;
import com.ndp.fb.redis.api.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: PageRdbServiceImpl.java
 * @Copyright: Copyright © 2015
 * @Description: 
 * @Company: yeahmobi
 * @Created on 上午10:43:20
 * @author giser.yang
 */
@Service
public class PageRdbServiceImpl extends DaoTemplate implements PageRdbService {

    @Autowired
    private RedisClient redisClient;
	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月19日 上午10:43:50      
	 * @param userId
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#getPagesByUserId(java.lang.String)     
	 */  
	    
	@Override
	public List<Page> getPagesByUserId(String userId) {
		String sql = "SELECT DISTINCT"
				+" page.id,"
				+" fb_user.user_id,"
				+" page.fb_page_id,"
				+" page.can_post,"
				+" page.category,"
				+" page.has_anded_app,"
				+" page.is_community_page,"
				+" page.is_published,"
				+" page.likes,"
				+" page.link,"
				+" page.`name`,"
				+" page.picture_url,"
				+" page.talking_about_count,"
				+" page.were_here_count"
				+" FROM"
				+" fb_user"
				+" INNER JOIN fb_userpermissions_pages ON fb_user.fb_user_id = fb_userpermissions_pages.fb_user_id"
				+" INNER JOIN page ON fb_userpermissions_pages.page_id = page.fb_page_id where fb_user.user_id = ?"
				+" and fb_userpermissions_pages.role IN ( 'MANAGER', 'CONTENT_CREATOR' ,'ADVERTISER' ,'MODERATOR') and page.is_published = 1";
		
		return getJdbcTemplate().query(sql, new Object[]{userId}, DefaultRowMapper.autoRowMapper(Page.class));
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月19日 上午10:43:50      
	 * @param page
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#savePage(com.ndp.fb.rdb.model.Page)     
	 */  
	    
	@Override
	public Long savePage(Page page) {
		return saveResultId(page);
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月19日 上午10:43:50      
	 * @param pageId
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#getPageByPageId(java.lang.Long)     
	 */  
	    
	@Override
	public Page getPageByPageId(Long pageId) {
		String sql = "select * from page where fb_page_id = ?";
		return findOne(sql, new Object[]{pageId}, DefaultRowMapper.autoRowMapper(Page.class));
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月19日 上午11:30:57      
	 * @param page
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#updatePage(com.ndp.fb.rdb.model.Page)     
	 */  
	    
	@Override
	public Integer updatePage(final Page page) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		return getJdbcTemplate().update(new  PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				String sql = "update page set can_post = ?,category = ?,has_anded_app = ?,is_community_page = ?,is_published = ?,likes = ?,link = ?,name = ?,picture_url = ?,talking_about_count = ?,were_here_count = ?"
						+ " where fb_page_id = ?";
				PreparedStatement ps = con.prepareStatement(sql,
						Statement.RETURN_GENERATED_KEYS);
				ps.setObject(1, page.getCanPost());
				ps.setObject(2, page.getCategory());
				ps.setObject(3, page.getHasAndedApp());
				ps.setObject(4, page.getIsCommunityPage());
				ps.setObject(5, page.getIsPublished());
				ps.setObject(6, page.getLikes());
				ps.setObject(7, page.getLink());
				ps.setObject(8, page.getName());
				ps.setObject(9, page.getPictureUrl());
				ps.setObject(10, page.getTalkingAboutCount());
				ps.setObject(11, page.getWereHereCount());
				ps.setObject(12, page.getFbPageId());
				return ps;
			}
		}, keyHolder);
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月19日 上午11:30:57      
	 * @param page
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#saveorupdatePage(com.ndp.fb.rdb.model.Page)     
	 */  
	    
	@Override
	public Long saveorupdatePage(Page page) {
		String key = "PAGE"+page.getFbPageId();
		if(!redisClient.setNx(key, page)){
			return 0L;
		}
		
		try {
			redisClient.expire(key, 5, TimeUnit.SECONDS.name());
			//这里加个乐观锁保证不会重复录入
			Page page1 = this.getPageByPageId(page.getFbPageId());
			if (page1 != null) {
				this.updatePage(page);
				return page1.getId();
			} else {
				return this.savePage(page);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			redisClient.delete(key);
		}
		return 0L;
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月25日 下午7:26:26      
	 * @param userId
	 * @param roles
	 * @return     
	 * @see com.ndp.fb.rdb.api.PageRdbService#getPagesByUserIdAndIsPost(java.lang.String, int, java.lang.String[])     
	 */  
	    
	@Override
	public List<Page> getPagesByUserIdAndIsPost(String userId, int is_published,
			String... roles) {
		String strRoles = "";
		if(roles!=null&&roles.length>0){
			for(String role:roles){
				strRoles+="'"+role+"'";
				strRoles+=",";
			}
		}else{
			return null;
		}
		String sql = "SELECT DISTINCT"
				+" page.id,"
				+" fb_user.user_id,"
				+" page.fb_page_id,"
				+" page.can_post,"
				+" page.category,"
				+" page.has_anded_app,"
				+" page.is_community_page,"
				+" page.is_published,"
				+" page.likes,"
				+" page.link,"
				+" page.`name`,"
				+" page.picture_url,"
				+" page.talking_about_count,"
				+" page.were_here_count"
				+" FROM"
				+" fb_user"
				+" INNER JOIN fb_userpermissions_pages ON fb_user.fb_user_id = fb_userpermissions_pages.fb_user_id"
				+" INNER JOIN page ON fb_userpermissions_pages.page_id = page.fb_page_id where fb_user.user_id = ?"
				+" and fb_userpermissions_pages.role IN ( "+strRoles+") and page.is_published = ?";
		
		return getJdbcTemplate().query(sql, new Object[]{userId,is_published},DefaultRowMapper.autoRowMapper(Page.class));
	}

}
